package dht.message;
import dht.*;

import java.nio.ByteBuffer;

public abstract class Message {

    // feel free to change this value it was arbitrary
    public static final int MAX_LENGTH = 50; // bytes

    public abstract byte[] getBytes();
    private final OpCode opCode;

    public OpCode getOpCode() {
        return opCode;
    }
    private HostAddress addr;

    public HostAddress getAddress() {
        synchronized (this) {
            return addr;
        }
    }
    
    private void setAddress(HostAddress addr) {
        synchronized (this) {
            this.addr = addr;
        }
    }

    public Message(OpCode opCode, HostAddress addr) {
        this.opCode = opCode;
        this.addr = addr;
    }

    public Message(byte[] message, HostAddress addr) {
        this.opCode = getOpCodeFromBytes(message);
        this.addr = addr;
    }

    public static OpCode getOpCodeFromBytes(byte[] bytes) {
        if (bytes.length < 2) {
            throw new IllegalArgumentException(
                    "OpCode is the first two bytes of any message");
        }

        return OpCode.convert(ByteBuffer.wrap(bytes).getShort());
    }

    
    public static OperationType getOperationType(byte[] bytes) {
        if (bytes.length < 2) {
            throw new IllegalArgumentException("OpCode is the first two bytes of any message");
        }
        return OperationType.convert(ByteBuffer.wrap(bytes).getShort(4));
    }
    
    @Override
    public String toString() {
        return this.opCode.toString() + " message from  " + this.getAddress().hostName();
    }
}
